<?php
/**
 *
 * @author griever
 * @version 
 */

require_once 'Base.php';

/**
 * SocketConnect Action Helper 
 * 
 * @uses actionHelper Custom_Helper
 */
class Custom_Helper_SocketConnect extends Dummy_Helper_Base {
	
	protected $family = AF_INET;
	
	protected $type = SOCK_STREAM;
	
	protected $protocol = SOL_TCP;
	
	public function setDomain($family)	{
		$this->family = $family;		
	}
	
	public function setType($type)	{
		$this->type = $type;
	}
	
	public function setProtocol($protocol)	{
		$this->protocol = $protocol;
	}
	
	private function getSocketErrorMsg($message, $socket = null)	{
		return $message.":".socket_strerror(socket_last_error());
	}
	
	/**
	 * 
	 * Establish a connection to the host at specified port, write data to it and close the socket
	 * @param unknown_type $host
	 * @param unknown_type $port
	 * @param unknown_type $data
	 */
	public function socketConnect($host, $port, $data)	{
		$socket = @socket_create($this->family, $this->type, $this->protocol);
		if ($socket == null)	{
			throw new Zend_Exception($this->getSocketErrorMsg("socket_create failed"));
		}
		$result = @socket_connect($socket, $host, $port);
		if ($result === false)	{
			throw new Zend_Exception($this->getSocketErrorMsg("socket_connect failed"));
		}
		$result = @socket_write($socket, $data);
		if ($result === false)	{
			throw new Zend_Exception($this->getSocketErrorMsg("socket write failed"));
		}
		socket_close($socket);
	}
	
	/**
	 * Strategy pattern: call helper as broker method
	 */
	public function direct($host, $port, $data) {
		// TODO Auto-generated 'direct' method
		return $this->socketConnect($host, $port, $data);
	}
}
